/*
*         (C) COPYRIGHT NBI Limited
*              ALL RIGHT RESERVED
*
* File        : fastflow/core/status.cc
* Authors     : dzhang
* Create Time : 2021/09/04 19:07:24
* Description :
*
*/

#include "fastflow/core/status.h"
#include <assert.h>
#include "fastflow/core/string_utils.h"

namespace fastflow {

Status::Status(StatusCategory category, int code, const std::string& msg) {
  assert(static_cast<int>(StatusCode::OK) != code);
  state_.reset(new State(category, code, msg));
}

Status::Status(StatusCategory category, int code)
    : Status(category, code, EmptyString()) {}

bool Status::IsOK() const noexcept {
  return (state_ == NULL);
}

StatusCategory Status::Category() const noexcept {
  return IsOK() ? StatusCategory::NONE : state_->category;
}

int Status::Code() const noexcept {
  return IsOK() ? static_cast<int>(StatusCode::OK) : state_->code;
}

const std::string& Status::ErrorMessage() const {
  return IsOK() ? EmptyString() : state_->msg;
}


std::string Status::ToString() const {
  if (state_ == nullptr) {
    return std::string("OK");
  }

  std::string result;

  if (StatusCategory::SYSTEM == state_->category) {
    result += "SystemError";
    result += " : ";
    result += std::to_string(errno);
  } else if (StatusCategory::FASTFLOW == state_->category) {
    result += "[FastFlowError]";
    result += " : ";
    result += std::to_string(Code());
    std::string msg;

    result += " : ";
    result += MLStatusToString(static_cast<MLStatus>(Code()));
    result += " : ";
    result += state_->msg;
  }

  return result;
}

const Status& Status::OK() noexcept {
  static Status s_ok;
  return s_ok;
}

const std::string& Status::EmptyString() {
  static std::string empty_str = "";
  return empty_str;
}

} // namespace fastflow